package com.ctg.itrdc.sysmgr.portal.interceptor;

import java.lang.reflect.Method;

import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.validation.BindingResult;

import com.ctg.itrdc.pasp.core.DTO;
import com.ctg.itrdc.sysmgr.portal.api.dto.BaseDTO;
import com.ctg.itrdc.sysmgr.portal.utils.DTOHelper;
//import org.springframework.aop.MethodBeforeAdvice;
/**
 * TODO 此处对controller无效果。暂无找到原因。
 * @author blackfox
 *
 */
//@Component("dtoInterceptor")
public class DTOInterceptor implements /*MethodBeforeAdvice*/  MethodInterceptor{

//	@Override
//	public void before(Method method, Object[] arguments,
//			Object paramObject) throws Throwable {
//		
//		if(method.getName().contains("insert")
//				||method.getName().contains("update")){
//			if(ArrayUtils.isNotEmpty(arguments) && arguments.length >2){
//				if (arguments[0] instanceof SysmgrBaseDTO) {
//					SysmgrBaseDTO dto = (SysmgrBaseDTO) arguments[0];
//					DTOHelper.updateDTO(dto);
//				}
//				if (arguments[1] instanceof BindingResult) {
//					BindingResult result = (BindingResult) arguments[1];
//					DTOHelper.valid(result);
//				}
//			}
//		}
//	}
	
	@Override
	public Object invoke(MethodInvocation invocation) throws Throwable {
		Method method = invocation.getMethod();
		if(method.getName().contains("insert")
				||method.getName().contains("update")){
			Object[] arguments = invocation.getArguments();
			if(ArrayUtils.isNotEmpty(arguments) && arguments.length >2){
				if (arguments[0] instanceof DTO) {
					BaseDTO dto = (BaseDTO) arguments[0];
					DTOHelper.updateDTO(dto);
				}
				if (arguments[1] instanceof BindingResult) {
					BindingResult result = (BindingResult) arguments[1];
					DTOHelper.valid(result);
				}
			}
		}
		return invocation.proceed();
	}

}
